/**
 * Created by shidaiapp on 2017/9/29.
 */

export const init = (tiyData) => {
  tiyData.tData.userList.length = 0;
  tiyData.tPage.total = 1;
  tiyData.tPage.startIndex = 0;
  tiyData.tPage.stepNumber = 60;
  tiyData.tPage.currentPage = 1;
  tiyData.tParams.searchParams.userState = 120;
  tiyData.tParams.searchParams.employeeName = "";
  tiyData.tParams.searchParams.employeeId = "";
  tiyData.tParams.searchParams.number = "";
  tiyData.tParams.searchParams.isNotAssigned = false;
  tiyData.tParams.searchParams.isHasShop = false;
  tiyData.tParams.searchParams.country = "";
  tiyData.tParams.searchParams.tags = "";
  tiyData.tParams.selectedUsers = [];
  tiyData.tParams.selectedEmployee = {};
};

/**
 * 从服务器请求列表
 * @param self
 * @param tiyData
 * @returns {Array}
 */
export const searchService = (self, tiyData) => {
  self.$Spin.show();
  let state = 120;
  if (tiyData.tParams.searchParams.userState!==''&&tiyData.tParams.searchParams.userState!==undefined){
    state = tiyData.tParams.searchParams.userState;
  } else {
    state = -1;
  }

  self.$apiPlugin.targetCustomerList({
    "pageSize": tiyData.tPage.stepNumber,
    "pageNum": tiyData.tPage.currentPage,
    "state" : state,
    "employeeId" : tiyData.tParams.searchParams.employeeId,
    "number" : tiyData.tParams.searchParams.number,
    "isNotAssigned": tiyData.tParams.searchParams.isNotAssigned,
    "isHasShop": tiyData.tParams.searchParams.isHasShop,
    "country": tiyData.tParams.searchParams.country,
    "tags": tiyData.tParams.searchParams.tags,
    "otherTags":tiyData.tParams.searchParams.otherTags
  }).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      let userPage = response.result;
      tiyData.tPage.total = userPage.total;
      tiyData.tData.userList.splice(0, tiyData.tData.userList.length);
      userPage.list.forEach(
        function (item) {
          tiyData.tData.userList.push(item);
          if (item.state === 310){
            item._disabled = true;
          }
        }
      );
      self.selectedIds.splice(0);
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
};

function sortKey(a,b){
  if(a.userShop != '' && b.userShop == '' ){
      return -1;
  }else if(a.userShop == '' && b.userShop != ''){
    return 1;
  }else {
    return 0;
  }
}

/**
 * 查询员工
 * @param self
 * @param tiyData
 * @param showCompent 查询推广员工后显示的组件
 * @returns {Array}
 */
export const getEmployees = (self, tiyData) => {
  // self.$Spin.show();
  tiyData.tParams.selectedEmployee = {}; //清空之前选择的员工
  self.$apiRole.getPromoteEmployee({}).then(function (response) {
    if (response.success) {
      let employeeList = response.result;
      tiyData.tData.employeeList.splice(0, tiyData.tData.employeeList.length);
      employeeList.forEach(
        function (item) {
            tiyData.tData.employeeList.push(item);
        });
    } else {
      self.$Message.error(response.errorMessage);
    }
    // self.$Spin.hide();
  });
};

/**
 * 分配负责员工
 * @param self
 * @param tiyData
 * @returns {Array}
 */
export const assignEmployee = (self, tiyData) => {
  self.$Spin.show();
  let userIds = [];
  tiyData.tParams.selectedUsers.forEach(user =>{
    userIds.push(user.id);
  });
  let data = {
    "employeeId":tiyData.tParams.selectedEmployee.id,
    "employeeName":tiyData.tParams.selectedEmployee.userName,
    "userIds":userIds
  }
  self.$apiPlugin.assignToEmployee(data).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      self.$Message.success("分配负责员工成功。");
      tiyData.tParams.selectedUsers=[];
      searchService(self, tiyData);
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
};

/**
 * 废弃用户
 * @param self
 * @param tiyData
 * @returns {Array}
 */
export const deleteCustomers = (self, tiyData) => {
  self.$Spin.show();
  let userIds = [];
  tiyData.tParams.selectedUsers.forEach(user =>{
    let userMap = {};
    userMap.id = user.id;
    userMap.state = user.state;
    userIds.push(userMap);
  });
  self.$apiPlugin.deleteCustomers(userIds).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      self.$Message.success("废弃用户成功。");
      searchService(self, tiyData);
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
};

/**
 * 从服务器请求客户详情
 * @param self
 * @param tiyData
 * @returns {Array}
 */
export const getCustomerDetail = (self, tiyData, id, state) => {
  self.$Spin.show();
  self.$apiPlugin.getCustomerInfoById({ "customerId": id,"state":state }).then(function (response) {
    self.$Spin.hide();
    self.$ySpliceAll(tiyData.tData.customerInfo.tags, tiyData.tData.customerInfo.readonlyTags,
      tiyData.tData.customerInfo.otherTags, tiyData.tData.customerInfo.contacts,tiyData.tData.customerInfo.opRecords)
    if (response.success) {
      let result = response.result;

      tiyData.tData.customerInfo.id = result.id;
      tiyData.tData.customerInfo.name = result.name;
      switch(result.channel){
        case 1:
          tiyData.tData.customerInfo.channel = "Instagram";
          break;
        case 2:
          tiyData.tData.customerInfo.channel = "Shopify";
          break;
        case 3:
          tiyData.tData.customerInfo.channel = "BigCommerce";
          break;
        case 5:
          tiyData.tData.customerInfo.channel = "线下采集";
          break;
        default:
          tiyData.tData.customerInfo.channel = "";
          break;
      }

      tiyData.tData.customerInfo.avatar = result.avatar;
      tiyData.tData.customerInfo.externalUrl = result.externalUrl;
      tiyData.tData.customerInfo.fullName = result.fullName;
      tiyData.tData.customerInfo.email = result.email;
      tiyData.tData.customerInfo.externalEmail = result.externalEmail;
      tiyData.tData.customerInfo.state = result.state;
      tiyData.tData.customerInfo.stateTitle = self.targetCustomerStateDict.filter(item => item.value == result.state)[0].name;
      tiyData.tData.customerInfo.number = result.number;
      // tiyData.tParams.customerInfo.description = result.description;
      tiyData.tData.customerInfo.employeeId = result.employeeId;
      tiyData.tData.customerInfo.employeeName = result.employeeName;
      tiyData.tData.customerInfo.createtime = self.$tiyBJTime(result.createtime);
      tiyData.tData.customerInfo.country = result.country;
      tiyData.tData.customerInfo.contactUrl = result.contactUrl;

      if(result.customerTagList.length>0){
        result.customerTagList.forEach(function(item,index){
          switch(item.type) {
            case 1:
              tiyData.tData.customerInfo.readonlyTags.push(item.tag);
              break;
            case 2:
              tiyData.tData.customerInfo.tags.push(item.tag);
              break;
            case 9:
              tiyData.tData.customerInfo.otherTags.push(item.tag);
              break;
          }
        })
      }
      if(result.customerExtendInfo){
        tiyData.tData.customerInfo.extendInfo = Object.assign({},result.customerExtendInfo);
        tiyData.tData.customerInfo.extendInfo.facebook=formatContactUrl(tiyData.tData.customerInfo.extendInfo.facebook);
        tiyData.tData.customerInfo.extendInfo.twitter=formatContactUrl(tiyData.tData.customerInfo.extendInfo.twitter);
        tiyData.tData.customerInfo.extendInfo.instagram=formatContactUrl(tiyData.tData.customerInfo.extendInfo.instagram);
        tiyData.tData.customerInfo.extendInfo.pinterest=formatContactUrl(tiyData.tData.customerInfo.extendInfo.pinterest);
      }

      if(result.customerContacts &&result.customerContacts.length>0){
        result.customerContacts.forEach(function(item,index){
          tiyData.tData.customerInfo.contacts.push(item)
        })
      }

      result.opRecords.forEach(function (item) {
        let record = item;
        record.employeeName = tiyData.tData.customerInfo.employeeName;
        tiyData.tData.customerInfo.opRecords.push(record);
      });
      tiyData.tStatus.modalCustomerInfo.isShow = true;
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
};


function formatContactUrl(url){
  if(url!=''&&url!=null && url.indexOf('?')!=-1){
    return url.substring(0,url.indexOf('?'));
  }
  return url;
}
